package com.qf.listener;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @author sunyamei
 * @version V1.0
 * @Project javase2203
 * @Package com.qf.listener
 * @Description:
 * @Date 2022/8/9 15:02
 */
@Component
public class TestQueue3Listener {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(queues = "queue3")
    public void messageHandler(String msg, Channel channel, Message message) throws Exception {
        //1. 获取消息唯一id
        String messageId = (String)message.getMessageProperties().getHeaders().get("spring_returned_message_correlation");

        //2. 设置key是消息唯一id, value是消息内容, 超时时间10秒, 存入redis, 使用setnx命令存入
        if (redisTemplate.opsForValue().setIfAbsent(messageId, msg, 10, TimeUnit.SECONDS)) {
            try {
                //3. 如果成功存入, 执行业务
                System.out.println("====接收方3====" + msg);

                //业务执行成功, 返回ack手动确认消息
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

            } catch (Exception e) {
                e.printStackTrace();
                //业务执行失败, 返回手动nack消息
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        } else {
            //4. 如果无法成功存入说明重复消费, 直接返回手动ack确认
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }


    }
}